import random  # 导入生成随机数包
import datetime
import time

from fastapi import APIRouter, HTTPException
from starlette import status
import jwt
from pydantic import BaseModel

from backend.app.app.crud_sys.query import get_admin_pwd, get_all_admin
from backend.app.app.api.api_v1.user import token1, verify_token_user
from backend.app.app.crud_sys.add import add_newadmin
from backend.app.app import rsa_private_key
from backend.app.app.api.utils.encryption import rsa_decrypt, rsa_encrypt
from backend.app.app.models.admin import admin_infom, save_lib_fra, save_user, admin_info_revise, Admin_Info_Data, \
    Admin_Page,Return_Data
from backend.app.app.crud_sys.tb_userorg_framework import query_all, add_inf, del_inf, updata_inf
from backend.app.app.crud_sys.tb_user import get_all_user_inf
from backend.app.app.models.user import name_pwd
from backend.app.app.crud_sys.query import get_admin_inf, get_admin_leP_id
from backend.app.app.crud_sys.tb_admin import admin_add_user, admin_del_user, admin_update_user, revise_admin, \
    get_old_ad, reurn_info_table2_data, reurn_info_table1_data, save_info_table_data2, save_info_table_data1, \
    save_admin_frame_data, reurn_admin_frame_data, updata_online_tb
from backend.app.app.api.api_v1.use_token import create_access_token, Depends, SECRET_KEY, ALGORITHM, turn_exp
from backend.app.app.crud_sys.tb_user import get_online_tb


admin_router = APIRouter(prefix="/admin", tags=["管理员"])

# Admin_token_efficient_time = 100
Admin_token_efficient_time = 1000
# Judge_toke_refresh = 10
Judge_toke_refresh = 100
save_admin_token = ""  # 记录token


# 验证当前管理员令牌
async def verify_token_admin(token: token1):
    token = token.token_data
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        # 验证令牌用户名，有效性，有效期
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        # 判断身份是否为admin
        if payload.get("status") != "admin":
            raise credentials_exception
        if username is None:
            raise credentials_exception
        # 判断令牌是否过期
        start = payload.get("iat")
        end = payload.get("exp")
        now = turn_exp()
        if now > payload.get("exp"):
            raise credentials_exception
    except Exception as e:
        print(e, e.__traceback__.tb_lineno, e.__traceback__.tb_frame.f_globals['__file__'])
        raise credentials_exception

    if (now - start) / 60 > Judge_toke_refresh:
        # 之前的令牌作废
        # 创立新的令牌并返回
        access_token = create_access_token(data={"sub": username}, expires_delta=Admin_token_efficient_time, avai=True,
                                           user_status="admin")
        return {"access_token": access_token, "token_type": "bearer", "user": username, "new": True}
    else:
        return {"user": username, "new": False, "access_token": token}


class id(BaseModel):
    user_id: str


class online_info(BaseModel):
    user_id: str
    online: int


@admin_router.post("/get_online", name="获取本单位在线人数")
async def get_online(user: id):
    online = get_online_tb(user.user_id)
    num = len(online)
    return {"Number_online": num}


@admin_router.post("/get_old_info", name="修改信息前信息")
async def get_old_info(u_id: id, ver=Depends(verify_token_admin)):
    all_info = get_old_ad(uid=u_id)
    return {"result": all_info, "verify": ver}


@admin_router.post("/revise_info", name="修改个人信息")
async def revise_info(information: admin_info_revise, ver=Depends(verify_token_admin)):
    re = revise_admin(user=information)
    return {"result": re, "verify": ver}


# 管理员对本法人单位用户管理
"""
前端:用户名，密码，所在部门，所在岗位，真实姓名，手机号码，电子邮箱，注册日期，授权状态，备注
"""


@admin_router.post("/save_base_inf", name="管理单位人员存库")
async def save_base_inf(user_inf: save_user, ver=Depends(verify_token_admin)):
    # 新增 add
    # 获取最新时间
    import datetime
    now = datetime.datetime.now().strftime("%Y-%m-%d")
    admin_inf = jwt.decode(ver['access_token'], SECRET_KEY, algorithms=[ALGORITHM])
    name = admin_inf.get("sub")
    l_id = get_admin_leP_id(name)
    a = False
    # 删除 delete
    b = False
    for user_id in user_inf.delete1:
        if user_id:
            b = admin_del_user(user_id)
    # 修改 modify
    c = False
    for i in user_inf.modify:
        if i:
            i.update({"Check_Date": now})
            i.update({"Check_Name": name})
            i.update({"Update_Date": now})
            i.update({"LegalPerson_ID": l_id[0]})
            c = admin_update_user(i)
    return {"add": a, "modify": c, "delete": b, "verify": ver}


# 管理员管理组织机构
@admin_router.post("/get_all_frame", name="管理框架读库,返回值有depart_id,增删改用，用户不可见")
async def get_all_frame(ver=Depends(verify_token_admin)):
    try:
        all = query_all()
        return {"information": all, "verify": ver}
    except:
        return {"information": "读取信息错误", "verify": ver}


# 管理人员管理组织结构存库
@admin_router.post("/save_all_frame", name="管理框架存库")
async def save_all_frame(fra_inf: save_lib_fra, ver=Depends(verify_token_admin)):
    print(fra_inf)
    # 新增 add
    a = False
    b = False
    c = False
    temp_list = []
    for i in fra_inf.add:
        if i:
            id = get_admin_leP_id(i["LegalPerson_ID"])
            i["LegalPerson_ID"] = id[0]
            temp_list.append(i["Depart_ID"])
            temp_list.append(i["Depart_Name"])
            temp_list.append(i["Depart_Rank"])
            temp_list.append(i["Belong_Depart_ID"])
            temp_list.append(i["Remark"])
            temp_list.append(i["LegalPerson_ID"])
            a = add_inf(temp_list)
    # 删除 delete
    for j in fra_inf.delete:
        b = del_inf(j["depart_ID"])
    # 修改 modify
    for k in fra_inf.modify:
        if k:
            id1 = get_admin_leP_id(k["LegalPerson_ID"])
            k["LegalPerson_ID"] = id1[0]
            temp_list.clear()
            temp_list.append(k["Depart_ID"])
            temp_list.append(k["Depart_Name"])
            temp_list.append(k["Depart_Rank"])
            temp_list.append(k["Belong_Depart_ID"])
            temp_list.append(k["Remark"])
            temp_list.append(k["LegalPerson_ID"])
            c = updata_inf(temp_list)
    return {"add": a, "modify": c, "delete": b, "verify": ver}


# 管理员管理人员
@admin_router.post("/get_all_inf", name="用户信息读库")
async def get_all_inf(ver=Depends(verify_token_admin)):
    try:
        all = get_all_user_inf()
        return {"information": all, "verify": ver}
    except:
        return {"information": "读取信息错误", "verify": ver}


@admin_router.post("/get_ver_code", name="获取验证码")
async def get_ver_code():
    code = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    ver_code = ""
    for i in range(4):
        new_code = random.choice(code)
        ver_code += new_code
    return {"ver_code": ver_code}


# 管理员登录
@admin_router.post("/login", name="管理员登录")
# name_pwd
async def judge_admin_pwd(name_pwd: name_pwd):  # 传入密码密文
    # 读取用户名
    all_user = get_all_admin()
    a = []
    for i in all_user:
        a.append(i[0])
    all_user = a
    # 根据用户名从数据库读取密码
    back_password = get_admin_pwd(name_pwd.username)
    ad_id = back_password[1]
    back_password = back_password[0]
    # 将前后端密码解密并判断
    front_password = rsa_decrypt(name_pwd.password, rsa_private_key)
    back_password = rsa_decrypt(back_password, rsa_private_key)
    if name_pwd.username not in all_user:
        print("not")
        return {"username": False, "password": False}
    else:
        if front_password == back_password:
            access_token = create_access_token(data={"sub": name_pwd.username},
                                               expires_delta=Admin_token_efficient_time,
                                               avai=True, user_status="admin")
            updata_online_tb(ad_id, 1)
            return {"username": True, "password": True, "access_token": access_token, "ID": ad_id}
        else:
            return {"username": True, "password": False}


# 管理员注册
@admin_router.post('/registe', name='注册管理员')
async def admin_registe(admin_inf: admin_infom):
    # 注册时间
    now = datetime.datetime.now().strftime("%Y-%m-%d")
    # 初始化信息
    try:
        userid = str(time.time()).replace('.','')[:10]
        pwd = rsa_encrypt(admin_inf.User_PWD)
        add_newadmin(update_date=now, register_date=now, check_date=None, user_id=userid,
                     user_pwd=pwd, remark=admin_inf.Remark,
                     user_name=admin_inf.User_Name, user_role=admin_inf.User_Role,
                     belong_depart=admin_inf.Belong_Depart,
                     job_name=admin_inf.Job_Name, user_truname=admin_inf.User_TruName,
                     user_mobilenumber=admin_inf.User_MobileNumber,
                     user_email=admin_inf.User_Email, legalperson_id=admin_inf.LegalPerson_ID,
                     isqualified=admin_inf.IsQualified, check_name=None)
        return True
    except Exception as e:
        print(e,e.__traceback__.tb_lineno)
        return False


# 获取管理员的基本信息
@admin_router.post("/return_inf", name="返回管理员，法人，部门")
async def return_inf():
    all = get_admin_inf()
    return {"information": all}


# 存储管理员管理框架界面表格数据
@admin_router.post("/save_frame_table_data", name="存储管理员框架表格数据")
async def save_frame_table(admin_info_data: Admin_Info_Data, ver=Depends(verify_token_user)):
    try:
        a = save_admin_frame_data(user_id=admin_info_data.User_ID,
                                  proj_id=admin_info_data.Proj_ID,
                                  frame_data=admin_info_data.Frame_Data)
        return {"result": a, "verify": ver}
    except:
        return False


# 返回管理员管理框架界面表格数据
@admin_router.post("/return_frame_table_data", name="返回管理员框架表格数据")
async def return_frame_table(return_data: Return_Data, ver=Depends(verify_token_user)):
    try:
        data = reurn_admin_frame_data(user_id=return_data.User_ID,
                                      proj_id=return_data.Proj_ID)

        return {"result": data, "verify": ver}
    except:
        return False


# 存储管理员界面用户信息表1数据
@admin_router.post("/save_admin_page1",
                   name="存储管理员界面用户信息表1数据 ")
async def save_admin_page1_data(admin_page: Admin_Page, ver=Depends(verify_token_user)):
    try:
        a = save_info_table_data1(user_id=admin_page.User_ID,
                                  proj_id=admin_page.Proj_ID,
                                  page_data=admin_page.Page_Data)

        return {"result": a, "verify": ver}
    except:
        return False


# 存储管理员界面用户信息表2数据
@admin_router.post("/save_admin_page2",
                   name="存储管理员界面用户信息表2数据 ")
async def save_admin_page2_data(admin_page: Admin_Page, ver=Depends(verify_token_user)):
    try:
        a = save_info_table_data2(user_id=admin_page.User_ID,
                                  proj_id=admin_page.Proj_ID,
                                  page_data=admin_page.Page_Data)

        return {"result": a, "verify": ver}

    except:
        return False


# 从管理员界面用户信息表1中返回数据
@admin_router.post("/return_admin_page1",
                   name="返回管理员界面用户信息表1数据")
async def return_admin_page1_data(return_data: Return_Data, ver=Depends(verify_token_user)):
    try:
        data = reurn_info_table1_data(user_id=return_data.User_ID,
                                      proj_id=return_data.Proj_ID)
        return {"result": data, "verify": ver}
    except:
        return False


# 从管理员界面用户信息表2中返回数据
@admin_router.post("/return_admin_page2",
                   name="返回管理员界面用户信息表2数据")
async def return_admin_page2_data(return_data: Return_Data, ver=Depends(verify_token_user)):
    try:
        data = reurn_info_table2_data(user_id=return_data.User_ID,
                                      proj_id=return_data.Proj_ID)
        return {"result": data, "verify": ver}
    except:
        return False
